/**
 * 版权所有(C)，上海勾芒信息科技，2016，所有权利保留。
 * 
 * 项目名：	cards-web
 * 文件名：	CheckRequestFilter.java
 * 模块说明：	
 * 修改历史：
 * 2016年5月4日 - Debenson - 创建。
 */
package com.alex.insistence.rest.provider;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;

import com.alex.insistence.rest.common.MyExceptionCode;
import com.alex.wechat.app.config.WxAppContext;
import com.gomore.jeecg.rest.common.RsResponse;
import com.gomore.jeecg.rest.utils.ResponseBuilderTool;
import com.google.common.collect.Lists;

/**
 * 用来初始化微信小程序第三方session。
 * 
 * @author Debenson
 * @since 0.1
 */
public class LoginRequestFilter implements ContainerRequestFilter, InitializingBean {

  private List<String> excludesUrls = new ArrayList<String>();

  @Override
  public void filter(ContainerRequestContext requestContext) throws IOException {
    final String url = requestContext.getUriInfo().getPath();
    if (matached(url)) {
      return;
    }

    String thirdSessionKey = getParameter(requestContext, WxAppContext.KEY_THIRD_SESSION_KEY);
    if (StringUtils.isNotBlank(thirdSessionKey)) {
      WxAppContext.setThirdSessionKey(thirdSessionKey);
      if (WxAppContext.getThirdSession() != null) {
        return;
      }
    }

    RsResponse respData = new RsResponse(MyExceptionCode.notLogin);
    requestContext.abortWith(ResponseBuilderTool.jsonResponse(respData).build());
  }

  private String getParameter(ContainerRequestContext requestContext, String key) {
    String value = requestContext.getHeaderString(key);
    if (StringUtils.isNotBlank(value)) {
      return value;
    }

    value = (String) requestContext.getProperty(key);
    return value;
  }

  /** 排除的url列表 */
  public List<String> getExcludesUrls() {
    return excludesUrls;
  }

  public void setExcludesUrls(List<String> excludesUrls) {
    this.excludesUrls = excludesUrls;
  }

  private List<Pattern> patterns = Lists.newArrayList();

  private boolean matached(String url) {
    for (Pattern p : patterns) {
      Matcher m = p.matcher(url);
      if (m.find()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    if (getExcludesUrls() != null) {
      for (String str : getExcludesUrls()) {
        patterns.add(Pattern.compile(str));
      }
    }
  }

}
